package BehaviorModel.iterorModel;

import java.util.Iterator;

public class ComputerCollege implements College{

    private Department[] departments;
    // departments 数组中的元素的下标
    private int numOfDepartment = 0;

    private Iterator iteratorArray;
    public ComputerCollege(Department[] departments) {
        this.departments = departments;
        this.numOfDepartment = departments.length - 1;
    }

    @Override
    public String getName() {
        return "计算机院系";
    }

    @Override
    public void addDepartment(Department department) {
        Department[] targetDepartments = new Department[departments.length+1];
        System.arraycopy(departments, 0, targetDepartments, 0, departments.length);
        targetDepartments[++numOfDepartment] = department;
        this.departments=targetDepartments; // 这你采用了浅拷贝
        createIterator();
    }


    @Override
    public void removeDepartment(Department department) {
        for (int index = 0; index < departments.length; index++) {
            if (departments[index].equals(department)) {
                swapAndRemoveItem(index);
            }
        }

    }

    private void swapAndRemoveItem(int index) {
        if (index!= numOfDepartment){
            Department temp = departments[index];
            departments[index] = departments[numOfDepartment];
            departments[numOfDepartment] = temp;
        }
        departments[numOfDepartment] = null;
        numOfDepartment--;
    }

    @Override
    public Iterator createIterator() {
        if (null == this.iteratorArray){
            this.iteratorArray = new ComputerIteror(departments);
        }else {
            ComputerIteror c = (ComputerIteror)this.iteratorArray;
            c.setDepartments(this.departments);
        }
        return this.iteratorArray;
    }
}
